package com.eascs.afterloancheck.dao.Impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.eascs.admin.common.dao.BaseO2oDao;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.afterloancheck.dao.LoanCheckDao;
import com.eascs.afterloancheck.entity.CheckLoanEntity;
import com.eascs.afterloancheck.form.CheckLoanQueryForm;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;

@Repository
public class LoanCheckDaoImpl extends BaseO2oDao implements LoanCheckDao {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private static final String table_name = "after_loan_check";
	private static final String status = "2";

	@Override
	public PageResult<Object[]> queryListPage(CheckLoanQueryForm form) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, form.getPageSize(),
				form.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		/*querySql.append(
				" SELECT id , revisit_code , bill_code , loan_user_name , org_manager , loan_type , revisiter_name , DATE_FORMAT(revisit_date,'%Y-%m-%d') , "
						+ " DATE_FORMAT(create_date,'%Y-%m-%d') , wf_status FROM after_loan_check WHERE 1=1 ");
		*/
		
		querySql.append(
				" SELECT alc.id , alc.revisit_code , alc.bill_code , alc.loan_user_name , alc.org_manager , alc.loan_type , alc.revisiter_name , DATE_FORMAT(alc.revisit_date,'%Y-%m-%d') , "
						+ " DATE_FORMAT(alc.create_date,'%Y-%m-%d') , alc.wf_status FROM after_loan_check alc LEFT JOIN o2o_loanapply l on l.bill_code = alc.bill_code WHERE  ");
		
		querySql.append(" 1=1 and (l.creat_ro="+UserHolder.getUser().getNo());
		if (!StringUtils.isEmpty(form.getXdjlNo())) {
			querySql.append(" or l.operator_no in ("+form.getXdjlNo()+"))");
		}else {
			querySql.append(" or /**DATA_PERMISSION(l.ltd)**/ 1=1 ) ");
		}
		
		if (StringUtil.isNotBlank(form.getBillCode())) {
			querySql.append(" AND alc.bill_code = ?");
			sqlPageQuery.addParam(form.getBillCode());

		}
		if (StringUtil.isNotBlank(form.getLoanUserName())) {
			querySql.append(" AND alc.loan_user_name like ?");
			sqlPageQuery.addLikeParam(form.getLoanUserName());

		}
		if (StringUtil.isNotBlank(form.getOrgManager())) {
			querySql.append(" AND alc.org_manager like ?");
			sqlPageQuery.addLikeParam(form.getOrgManager());

		}
		if (StringUtil.isNotBlank(form.getRevisiterName())) {
			querySql.append(" AND alc.revisiter_name like ?");
			sqlPageQuery.addLikeParam(form.getRevisiterName());

		}
		querySql.append(" ORDER BY alc.CREATE_DATE DESC ");
		sqlPageQuery.setQuerySql(querySql.toString());
		return this.findDataWithPage(sqlPageQuery);
	}

	@Override
	public CheckLoanEntity insertCheckLoanEntity(CheckLoanEntity entity) {
		if (entity == null) {
			return null;
		}
		int result = this.insert(entity);
		if (result > 0) {
			return entity;
		}
		return null;
	}

	@Override
	public CheckLoanEntity queryEntityById(String parameter) {
		return this.getById(CheckLoanEntity.class, parameter);
	}

	@Override
	public boolean processRevisitStart(String parameter) {
		String sql = "UPDATE " + table_name + " SET wf_status=? WHERE id=?";

		int result = this.execute(sql, new Object[] { ProcessTaskMain.PROECESS_STATUS_HANDING, parameter });
		return result > 0 ? true : false;
	}

	@Override
	public boolean updateRevisitWfStatus(String paramater, int wfStatus) {
		String sql = "UPDATE " + table_name + " SET wf_status=? WHERE reffer_id=?";

		int result = this.execute(sql, new Object[] { wfStatus, paramater });
		return result > 0 ? true : false;
	}

	@Override
	public CheckLoanEntity queryEntityByReferId(String parameter) {
		String sql = "SELECT * FROM AFTER_LOAN_CHECK C WHERE C.reffer_id = ? ";
		return this.findEntity(sql, CheckLoanEntity.class, parameter);
	}

	@Override
	public boolean updateEntityById(CheckLoanEntity entity) {
		// TODO Auto-generated method stub
		int result = this.updateById(entity);
		return result > 0 ? true : false;
	}

	/**
	 * 校验是否上传附件
	 */
	@Override
	public boolean checkCodeAttachment(String loanapplyNo, String code) {
		boolean flag = true;
		String sql = "select d.datalist_code from o2o_datalist d where d.is_delete=? and d.loanapply_no=? and d.datalist_code=?";
		List<String> codelist = this.findSimpleObjectList(sql, String.class, StatusContexts.O2O_NO, loanapplyNo, code);
		logger.info("查询附件次数：" + codelist.size());
		if (codelist != null && codelist.size() > 0) {
			if (!codelist.contains(code)) {
				flag = false;
			}
		} else {
			flag = false;
		}
		logger.info("查询flag：" + flag);
		return flag;
	}

	@Override
	public Integer queryLoanNum(String loanId) {
		String sql = "SELECT LOAN_NUM FROM O2O_AFTER_LOAN_FOR_CUSTOMER C WHERE C.CUSTOMER_ID = ?";
		return this.findInteger(sql, loanId);
	}

	@Override
	public PageResult<Object[]> listCheckLoanEntity(String billCode) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Integer.MAX_VALUE, 0);
		String querySql = "SELECT C.ID , C.REVISIT_CODE , C.SPONSOR_NAME , C.REVISITER_NAME , C.REVISIT_DATE , C.REVISIT_FORM , C.REVISIT_TYPE , C.MONTHLY_SALE , "
				+ "C.NEW_DEBT , C.WF_STATUS FROM AFTER_LOAN_CHECK C WHERE BILL_CODE = ?";
		sqlPageQuery.addParam(billCode);
		sqlPageQuery.setQuerySql(querySql);
		return this.findDataWithPage(sqlPageQuery);
	}

	@Override
	public Boolean isStartFlow(String billCode) {
		String sql = "SELECT * FROM after_loan_check WHERE bill_code = ? AND wf_status = ?";
		List<CheckLoanEntity> findEntitys = this.findEntitys(sql, CheckLoanEntity.class, billCode,
				LoanCheckDaoImpl.status);

		if (findEntitys.size() != 0) {
			return true;
		}
		return false;
	}

	@Override
	public CheckLoanEntity queryEntityByBillCode(String billCode) {
		String sql = "SELECT * FROM AFTER_LOAN_CHECK C WHERE C.bill_code = ? ";
		return this.findEntity(sql, CheckLoanEntity.class, billCode);
	}

	@Override
	public Boolean deleteEntity(CheckLoanEntity entity) {

		int execute = this.deleteById(CheckLoanEntity.class, entity.getId());
		if (execute > 0) {
			return true;
		}

		return false;

	}

	@Override
	public boolean updateCreateTime(String parameter) {
		String sql = "UPDATE " + table_name + " SET create_date=? WHERE id=?";

		int result = this.execute(sql, new Object[] { new Date(), parameter });
		return result > 0 ? true : false;
	}

}
